﻿/*
*
* jCaret Plugin
*
 *
 * Copyright (c) 2010 C. F., Wong (<a href="http://cloudgen.w0ng.hk">Cloudgen Examplet Store</a>)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
﻿(function(k,e,i,j){k.fn.caret=function(b,l){var a,c,f=this[0],d=k.browser.msie;if(typeof b==="object"&&typeof b.start==="number"&&typeof b.end==="number"){a=b.start;c=b.end}else if(typeof b==="number"&&typeof l==="number"){a=b;c=l}else if(typeof b==="string")if((a=f.value.indexOf(b))>-1)c=a+b[e];else a=null;else if(Object.prototype.toString.call(b)==="[object RegExp]"){b=b.exec(f.value);if(b!=null){a=b.index;c=a+b[0][e]}}if(typeof a!="undefined"){if(d){d=this[0].createTextRange();d.collapse(true);
d.moveStart("character",a);d.moveEnd("character",c-a);d.select()}else{this[0].selectionStart=a;this[0].selectionEnd=c}this[0].focus();return this}else{if(d){c=document.selection;if(this[0].tagName.toLowerCase()!="textarea"){d=this.val();a=c[i]()[j]();a.moveEnd("character",d[e]);var g=a.text==""?d[e]:d.lastIndexOf(a.text);a=c[i]()[j]();a.moveStart("character",-d[e]);var h=a.text[e]}else{a=c[i]();c=a[j]();c.moveToElementText(this[0]);c.setEndPoint("EndToEnd",a);g=c.text[e]-a.text[e];h=g+a.text[e]}}else{g=
f.selectionStart;h=f.selectionEnd}a=f.value.substring(g,h);return{start:g,end:h,text:a,replace:function(m){return f.value.substring(0,g)+m+f.value.substring(h,f.value[e])}}}}})(jQuery,"length","createRange","duplicate");

/*
* FIM
* jCaret plugin
*/


$.fn.selectRange = function (start, end)
{
    $(this).caret(start, end || start);
    /*
    * Remover este código se jCaret ok.
    *
    return this.each(function ()
    {
        if (this.setSelectionRange)
        {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange)
        {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
    */
};

$.fn.getSelectionRange = function ()
{
    /*
    * Remover este código se jCaret ok.
    *
    var _this = $(this);
    var e = this;
    if (e != document.activeElement)
        _this.focus();

    if (!(e.selectionStart != undefined && e.selectionEnd != undefined))
    {
        // The current selection
        var range = document.selection.createRange();
        // We'll use this as a 'dummy'
        var stored_range = range.duplicate();
        // Select all text
        stored_range.moveToElementText(e);
        // Now move 'dummy' end point to end point of original range
        stored_range.setEndPoint('EndToEnd', range);
        // Now we can calculate start and end points
        e.selectionStart = stored_range.text.length - range.text.length;
        e.selectionEnd = e.selectionStart + range.text.length;
    }
    return { start: e.selectionStart, end: e.selectionEnd, length: e.selectionEnd - e.selectionStart };
    */
    var caret = $(this).caret();
    caret.length = caret.end - caret.start;
    return caret;
};


$.fn.getCursorPos = function ()
{
    return $.fn.getSelectionRange.apply(this).start;
};

function direct_cfg_number_mask()
{
    var formatNumber = function (str)
    {
        var parts = utils.getFloatParts(str);
        if (parts.integer + parts.decimal == 0)
            return "0,00";
        else
        {
            return utils.stuffChars(parts.integer.toString(), "xxx.xxx.xxx.xxx", true) + "," + utils.stuffChars("00" + parts.decimal.toString(), "xx", true);
        }
    };

    var formatValue = function (val, divBy, normalize)
    {
        if (normalize)
        {
            var pos = Math.max(val.indexOf(','), val.indexOf('.'));
            if (pos == -1)
                val = val + ",00";
            else
            {
                var dif = val.length - pos - 1;
                if (val.length - 2 <= pos)
                    val = val + utils.padNumber(0, 2 - dif)
                else if (pos + 2 < val.length)
                    val = val.substring(0, pos + 3);
            }
        }
        return formatNumber((utils.parseFloat(utils.filterDigits(val)) / divBy).toString());
    };

    var formatAndSet = function (el, val, divBy, normalize, select)
    {
        // garantir que após a virgula tenha apenas 2 digitos
        var fmt = formatValue(val, divBy, normalize !== false);
        var currVal = el.val();
        if (select)
            var cursorPos = el.getSelectionRange().end - currVal.length + fmt.length;
        el.val(fmt);
        if (cursorPos)
            el.selectRange(cursorPos, cursorPos);
        return fmt;
    };

    $.fn.numberVal = function (newValue)
    {
        val = utils.convertToFloat($(this).val());
        if (newValue)
        {
            if (typeof newValue !== "number")
                newValue = utils.convertToFloat(newValue);
            $(this).val(formatValue(newValue.toString(), 100, true));
        }
        return val;
    };

    $(".number-mask").live("focus", function (e)
    {
        var _this = $(this);
        var val = _this.val();
        if (utils.convertToFloat(val) == 0)
            _this.val((val = "0,00"));
        else
            formatAndSet(_this, val, 100, true, false);
        setTimeout(function () { _this.select() }, 100);
    })
    .live("keydown", function (e)
    {
        var key = utils.getEventKey(e);
        var _this = $(this);
        $("<span/>").text("keyDown: " + key).appendTo($("body").append("<br/>"));
        var val = _this.val();
        if (utils.isDecimalSep(key) && _this.numberVal() != 0)
        {
            var fmt = formatAndSet(_this, val, 1, true, false);
            _this.selectRange(fmt.indexOf(',') + 1, fmt.length);
            $("<span/>").text("keyDown: " + key + " - prevent default").appendTo($("body").append("<br/>"));
            e.preventDefault();
        }
        else if (key == _keys.del)
        {
            _this.val("0,00");
            _this.select();
            e.preventDefault();
        }
        else if (key == _keys.backSpace)
        {
            var range = _this.getSelectionRange();
            if (!range.length)
                range.start = range.end - 1;
            formatAndSet(_this, val.substr(0, range.start) + val.substr(range.end), 100, false, false);
            _this.selectRange(range.start, range.start);
            e.preventDefault();
        }
    })
    .live("keypress", function (e)
    {
        var key = utils.getEventKey(e);
        if (utils.isDigitKey(key))
        {
            var _this = $(this);
            var val = _this.val();
            var range = _this.getSelectionRange();
            formatAndSet(_this, val.substr(0, range.start) + String.fromCharCode(key) + val.substr(range.end), 100, false, true);
            e.preventDefault();
        }
    })
    .live("keyup", function (e)
    {
        var key = utils.getEventKey(e);
        $("<span/>").text("keyUp: " + key).appendTo($("body").append("<br/>"));

        if (!utils.isDigitKey(key) && !utils.isDecimalSep(key) && key !== _keys.tab)
        {
            var _this = $(this);
            var val = _this.val();
            formatAndSet(_this, val, 100, utils.isSpecialKeyPressed(e), false);
        }
    })
    .live("blur", function (e)
    {
        $(this).val(formatNumber(utils.parseFloat($(this).val()).toString()));
    });
};
direct_cfg_number_mask();


function direct_cfg_date_mask()
{
    var formatAndSet = function (el, val, shortTime, changing)
    {
         var fmt = utils.joinDateParts(utils.splitDateString(val), shortTime ? "short" : false);
         if (changing){
            var range = el.getSelectionRange();
            var newPos = range.end - val.length + fmt.length;
            newPos = Math.min(newPos, fmt.length);
            el.val(fmt);
            el.selectRange(newPos,newPos);
         }
         else
            el.val(fmt);
    }

    var checkSlash = function (el)
    {
        var val = el.val();
        //verificar se é necessário adicionar a barra
        var bar1Pos = val.indexOf('/');
        // nenhuma barra
        if (bar1Pos == -1)
        {
            if (val.length == 2)
                el.val(val = val + '/');
        }
        //  1 barra
        else if ((val.lastIndexOf('/') == bar1Pos) && val.length - 3 == bar1Pos)
            el.val(val = val + '/');
        // 2 barras e hora
        else if (val.length==13)
            el.val(val = val + ":");
        return val;
    };

    $(".date-mask")
    .live("focus", function(e){
        var _this = $(this);
        var val = _this.val().trim();
        var isShort = _this.hasClass("date-short-time-mask");
        if (val.length)
            formatAndSet(_this, val, isShort, false);

        setTimeout(function(){
            _this.select();
        }, 100);
    })
    .live("keydown", function (e)
    {
        var key = utils.getEventKey(e);
        var _this = $(this);
        var isShortTime = _this.hasClass("date-short-time-mask");
        var val = _this.val();
        if (utils.isSlashKey(key) || utils.isDecimalSep(key))
        {
            if (val.length){
                var lastChar = val.substr(val.length - 1);
                var lastIsBar = lastChar == "/";
                var hasTwoBars = val.indexOf("/") != val.lastIndexOf("/");
                if (!lastIsBar && !hasTwoBars)
                {
                    //formatar o parametro
                    var slashPos = val.lastIndexOf("/");
                    if (slashPos == -1)
                        _this.val(utils.padNumber(val, 2) + "/");
                    else if (val.length == 4)
                        _this.val(val.substring(0, slashPos + 1) + utils.padNumber(val.substr(slashPos + 1, 1), 2) + "/");
                }
                else if (lastIsBar && hasTwoBars){
                    //tem duas barras e o ultimo caracter é uma barra, então colocar o ano atual
                    _this.val(val + (new Date()).getFullYear());
                }
                else if (hasTwoBars && val.length == 12)
                    _this.val(val.substr(0, 11) + utils.padNumber(val.substr(11).trim(), 2));
                else if (hasTwoBars && val.length <= 11)
                    formatAndSet(_this, val, false, true);
            }
            e.preventDefault();
        }
        var isDigitKey = utils.isDigitKey(key);
        if (!isDigitKey && !utils.isNavigationKey(key))
            e.preventDefault();
        if (key != _keys.backSpace && key != _keys.del)
        {
            var newVal = checkSlash(_this);
            if (newVal.length == 10 && isShortTime)
                _this.val(newVal + " ").selectRange(11,11);
        }
    })
    .live("keyup", function (e)
    {
        var _this = $(this);
        var val = _this.val();
        var key = utils.getEventKey(e);
        if (key != _keys.backSpace && key != _keys.del)
            checkSlash(_this);
    })
    .live("blur", function (e)
    {
        var _this=$(this);
        var val = _this.val().trim();
        if (val.length)
            formatAndSet(_this, val, _this.hasClass("date-short-time-mask"), false);
    });


};
direct_cfg_date_mask();


function direct_cfg_case_masks()
{
    var checkKey = function (el, event, upper)
    {
        var key = utils.getEventKey(event);
        var _this = $(el);
        var val = _this.val();
        var char = String.fromCharCode(key);
        char = upper ? char.toUpperCase() : char.toLowerCase();
        var range = _this.getSelectionRange();
        _this.val(val.substr(0, range.start) + char + val.substr(range.end));
        _this.selectRange(range.start + 1, range.start + 1);
        event.preventDefault();
    };


    $(".uppercase-mask")
    .live("keypress", function (e)
    {
        checkKey(this, e, true);
    })
    .live("blur", function (e)
    {
        $(this).val($(this).val().toUpperCase());
    });

    $(".lowercase-mask")
    .live("keypress", function (e)
    {
        checkKey(this, e, false);
    })
    .live("blur", function (e)
    {
        $(this).val($(this).val().toLowerCase());
    });
};
direct_cfg_case_masks();

function direct_cfg_int_mask()
{
    var formatNumber = function (value)
    {
        if (value == 0)
            return "0";
        else
        {
            return utils.stuffChars(value.toString(), "xxx.xxx.xxx.xxx", true);
        }
    };

    var formatAndSet = function (el, val)
    {
        var fmt = formatNumber(utils.parseInt(val));
        var currVal = el.val();
        var range = el.getSelectionRange();
        var newPos = range.start - currVal.length + fmt.length;
        el.val(fmt);
        el.selectRange(newPos, newPos);
    };

    $(".integer-mask, .short-mask").live("focus", function (e)
    {
        var _this = $(this);
        formatAndSet(_this, _this.val());
        var val = _this.val();
        setTimeout(function ()
        {
            _this.selectRange(val.length, val.length);
        }, 100);
    })
    .live("keydown", function (e)
    {
        var key = utils.getEventKey(e);
        var _this = $(this);
        var val = _this.val();
        if (key == _keys.del)
        {
            _this.val("0");
            _this.selectRange(1, 1);
            e.preventDefault();
        }
    })
    .live("keypress", function (e)
    {
        var key = utils.getEventKey(e);
        if (utils.isDigitKey(key))
        {
            var _this = $(this);
            var val = _this.val();
            var range = _this.getSelectionRange();
            formatAndSet(_this, val.substr(0, range.start) + String.fromCharCode(key) + val.substr(range.end));
            e.preventDefault();
        }
    })
    .live("keyup", function (e)
    {
        var key = utils.getEventKey(e);
        if (!utils.isDigitKey(key))
        {
            var _this = $(this);
            formatAndSet(_this, _this.val());
        }
    })
    .live("blur", function (e)
    {
        var _this = $(this);
        _this.val(formatNumber(utils.parseInt(_this.val())));
    });
};
direct_cfg_int_mask();

function direct_cfg_custom_mask()
{
    var formatAndSet = function (el, val, changing)
    {
        var currVal = el.val();
        var mask = el.attr("data-custom-mask");
        var fmt = utils.stuffChars(utils.filterDigits(val), mask);
        if (changing)
        {
            var range = el.getSelectionRange();
            el.val(fmt);
            var newPos = range.end - currVal.length + fmt.length;
            while (mask.substr(newPos, 1) != "x" && newPos < mask.length) { newPos++; }
            newPos = Math.min(newPos, fmt.length);
            el.selectRange(newPos, newPos);
        }
        else
            el.val(fmt);
    };

    $(".custom-mask").live("focus", function (e)
    {
        var _this = $(this);
        formatAndSet(_this, _this.val());
        setTimeout(function ()
        {
            _this.select();
        }, 100);
    })
    .live("keypress", function (e)
    {
        var key = utils.getEventKey(e);
        if (utils.isDigitKey(key))
        {
            var _this = $(this);
            var val = _this.val();
            var range = _this.getSelectionRange();
            formatAndSet(_this, val.substr(0, range.start) + String.fromCharCode(key) + val.substr(range.end), true);
            e.preventDefault();
        }
    })
    .live("keyup", function (e)
    {
        var key = utils.getEventKey(e);
        if (!utils.isDigitKey(key) && !utils.isNavigationKey(key) && !utils.isSpecialKeyPressed(e))
        {
            var _this = $(this);
            formatAndSet(_this, _this.val(), false);
        }
    })
    .live("blur", function (e)
    {
        var _this = $(this);
        formatAndSet(_this, _this.val(), false);
    });
};
direct_cfg_custom_mask();

